<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <title>Upload</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>

<body>
    <blockquote class="layui-elem-quote" style="margin: 15px 0;">请选择单个文件拖拽上传或批量选择本地文件上传</blockquote>


    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>拖拽上传</legend>
    </fieldset>
    <div style="text-align: center">
        <div class="layui-upload-drag" id="upload" style="display: inline-block;padding: 50px;width: 300px">
            <i class="layui-icon"></i>
            <p id="prompt" style="padding-top: 10px">点击上传，或将文件拖拽到此处</p>
        </div>
    </div>

    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>多文件列表</legend>
    </fieldset>


    <div class="layui-upload">
        <button type="button" class="layui-btn layui-btn-normal" id="list">选择多文件</button>
        <button type="button" class="layui-btn" id="listAction">开始上传</button>
        <div class="layui-upload-list">
            <table class="layui-table">
                <thead>
                    <tr>
                        <th>文件名</th>
                        <th>大小</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="fileList"></tbody>
            </table>
        </div>
    </div>

    <script src="/layui/layui.js" charset="utf-8"></script>
    <script src="/js/jquery.js"></script>
    <!-- 注意：如果你直接复制所有代码到本地，上述js路径需要改成你本地的 -->
    <script>
        layui.use(['upload', 'element'], function () {
            var $ = layui.jquery;
            var upload = layui.upload;
            var layer = layui.layer;
            var element = layui.element;
            var file = {
                fileSize: -1,
                percent: -1
            };

            //拖拽上传
            upload.render({
                elem: '#upload',
                accept: 'file',
                multiple: true,
                url: '/file/upload',
                before: function () {
                    layer.load();
                },
                done: function (res, index, upload) {
                    layer.closeAll('loading');
                    layer.msg('上传成功');
                    close();
                },
                progress: function () {
                    var ws;
                    connect();
                }
            });

            var fileListView = $('#fileList'),
                uploadListIns = upload.render({
                    elem: '#list',
                    url: '/file/upload', //改成您自己的上传接口
                    accept: 'file',
                    multiple: true,
                    auto: false,
                    bindAction: '#listAction',
                    choose: function (obj) {
                        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                        //读取本地文件
                        obj.preview(function (index, file, result) {
                            var tr = $(['<tr id="upload-' + index + '">', '<td>' + file.name +
                                '</td>', '<td>' + (file.size / 1024).toFixed(1) +
                                'kb</td>', '<td>等待上传</td>', '<td>',
                                '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
                                '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
                                '</td>', '</tr>'
                            ].join(''));

                            //单个重传
                            tr.find('.demo-reload').on('click', function () {
                                obj.upload(index, file);
                            });

                            //删除
                            tr.find('.demo-delete').on('click', function () {
                                delete files[index]; //删除对应的文件
                                tr.remove();
                                uploadListIns.config.elem.next()[0].value =
                                    ''; //清空 input file 值，以免删除后出现同名文件不可选
                            });
                            fileListView.append(tr);
                        });
                    },
                    before: function () {
                        layer.load();
                    },
                    done: function (res, index, upload) {
                        if (res.code === 200) { //上传成功
                            var tr = fileListView.find('tr#upload-' + index),
                                tds = tr.children();
                            tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                            tds.eq(3).html(''); //清空操作
                            return delete this.files[index]; //删除文件队列已经上传成功的文件
                        }
                        this.error(index, upload);
                    },
                    error: function (index, upload) {
                        var tr = fileListView.find('tr#upload-' + index),
                            tds = tr.children();
                        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                    },
                    allDone: function (obj) {
                        layer.closeAll('loading');
                        layer.msg("上传成功，共上传" + obj.total + "个文件，成功" + obj.successful + '个，失败' + obj
                            .aborted + '个。');
                    }
                });

            function connect() {
                if ("WebSocket" in window) {
                    ws = new WebSocket("ws://localhost:8090/fileWebsocket");

                    ws.onopen = function () {
                        console.log("连接成功");
                    };

                    ws.onmessage = function (evt) {
                        //接收服务端的推送信息，改变进度条
                        var data = JSON.parse(evt.data);
                        var text =
                            '文件上传中,文件大小：' + fileSize(data.fileSize) + ' 上传进度：' + data.percent + '%';
                        $("#prompt").html(text);
                        if (data.percent === 100) {
                            $("#prompt").html('点击上传，或将文件拖拽到此处');
                        }
                    };
                    ws.onclose = function () {
                        // 关闭 websocket
                        console.log("连接已关闭...");
                    };
                } else {
                    // 浏览器不支持 WebSocket
                    layer.msg("您的浏览器不支持 WebSocket!");
                }
            }
            //关闭websocket
            function close() {
                ws.close();
            }

            function fileSize(size) {
                if (size >= 1024) {
                    size /= 1024;
                    size = size.toFixed(2);
                    if (size >= 1024) {
                        size /= 1024;
                        size = size.toFixed(2);
                        if (size >= 1024) {
                            size /= 1024;
                            size = size.toFixed(2);
                            return size + 'GB';
                        } else {
                            return size + 'MB';
                        }
                    } else {
                        return size + 'KB';
                    }
                } else {
                    return size + 'B';
                }
            }
        });
    </script>

</body>

</html>